import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JPanel;

public class GUI_SubGridPanel extends JPanel implements MouseListener
{
	private SubGrid subGrid; 
	
	private int width; 
	private int height; 
	private int lineWidth; 
	private int cellWidth; 
	private int cellHeight; 
	
	
	
	public GUI_SubGridPanel(SubGrid s)
	{
		subGrid = s; 
		addMouseListener(this); 
	}
	
	public void draw(Graphics gr)
	{
		setBackground(Color.GREEN);
		Graphics2D g = (Graphics2D)gr; 
		g.setStroke(new BasicStroke(lineWidth));
		
		Dimension size = getSize(); 
		Insets inset = getInsets();
		
		width = size.width - inset.left - inset.right;
		height = size.height - inset.top - inset.bottom; 
		
		lineWidth = width/100;
		
		cellWidth = (width - lineWidth * 2)/3;
		cellHeight = (height - lineWidth * 2)/3;
		
		g.drawLine(cellWidth, 0, cellWidth, height);
		g.drawLine(cellWidth*2 + lineWidth, 0, cellWidth*2 + lineWidth, height);
		
		g.drawLine(0, cellHeight, width, cellHeight);
		g.drawLine(0, cellHeight*2 + lineWidth, width, cellHeight*2 + lineWidth);
		
		g.setColor(Color.BLUE);
		
		for( int i = 0; i < subGrid.getLength(); i++ )
		{
			for( int j = 0; j < subGrid.getLength(i); j++)
			{
				if( subGrid.get(i,j) != null )
				{
					int diameter = cellWidth/2;
					int radius = diameter/2; 
					int xcentr = cellWidth * i + (cellWidth/2);
					int ycentr = cellWidth * j + (cellHeight/2);
					int xcoord = xcentr - radius; 
					int ycoord = ycentr - radius; 
					
					g.fillArc(xcoord, ycoord, diameter, diameter, 0, 360);
				}
			}
		}
		
		
	}
	
	@Override
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		draw(g);
	}

	@Override
	public void mouseClicked(MouseEvent e) 
	{
		System.out.print("clicked! ");
		
		int x = e.getX(); 
		int y = e.getY(); 
		
		x -= lineWidth * (x/cellWidth); 
		y -= lineWidth * (y/cellHeight);
		
		int row = x/cellWidth;
		int col = y/cellHeight; 
		
		GridLocation loc = new GridLocation(subGrid.getMainGridRow(), subGrid.getMainGridCol(), row, col);
		subGrid.placePiece(new GamePiece(Color.BLUE, loc), loc); 
		draw(this.getGraphics());
	}

	@Override
	public void mouseEntered(MouseEvent e) 
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) 
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) 
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) 
	{
		// TODO Auto-generated method stub
		
	}
}
